import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { QueueName } from 'src/common/constants/queue.constant';
import { DemoService } from './demo.service';

export interface IDemoConsumer {
  name: string;
  categoryName: string;
  owner: string;
}

@Processor(QueueName.DEMO)
export class DemoConsumer extends WorkerHost {
  constructor(private readonly demoService: DemoService) {
    super();
  }

  async process(job: Job<any, any, string>): Promise<any> {
    console.log('job:', job);

    switch (job.name) {
      case 'create': {
        // 执行create SQL语句
        const data: IDemoConsumer = job.data;
        // const demoRepository = this.dataSource.getRepository(Demo);
        // const demoCategoryRepository =
        //   this.dataSource.getRepository(DemoCategory);

        // let category = await demoCategoryRepository.findOneBy({
        //   name: data.categoryName,
        // });
        // if (!category) {
        //   category = await demoCategoryRepository.save({
        //     name: data.categoryName,
        //   });
        // }
        // const demoExists = await demoRepository.existsBy({
        //   name: data.name,
        // });
        // if (!demoExists) {
        //   await demoRepository.save({
        //     name: data.name,
        //     categoryId: category.id,
        //     owner: data.owner,
        //   });
        // }
        await this.demoService.testTransaction(
          data.categoryName,
          data.name,
          data.owner,
        );

        break;
      }
      case 'delete': {
        // 执行delete SQL语句
      }
      default: {
        // do nothing
      }
    }
  }
}
